import zh from './language/zh';
import en from './language/en';
import api from 'js/api/index';

let language_zh = window.localStorage.getItem('language_zh');
if (language_zh) {
	try {
		language_zh = JSON.parse(language_zh)
	} catch (e) {
		language_zh = zh;
	}
} else {
	language_zh = zh;
}

let language_en = window.localStorage.getItem('language_en');
if (language_en) {
	try {
		language_en = JSON.parse(language_en)
	} catch (e) {
		language_en = en;
	}
} else {
	language_en = zh;
}

class I18n {
	static getInstance() {
		if (!I18n.instance) {
			I18n.instance = new I18n();
		}
		return I18n.instance;
	}
	constructor() {
		this.languageData = {
			'zh-CN': language_zh,
			'en': language_en
		};
	}
	get(code, params) {
		let map = this.languageMap || {};
		let key = map[code];
		if (this.language && key && this.language[key]) {
			var template = this.language[key];
			//   if (template && params) {
			//       return substitute(template, params);
			//   } else
			if (template) {
				return template;
			}
			return code;
		} else {
			return code;
		}
	}
	setLanguage(language) {
		this.languageName = language;
		this.language = this.languageData[language];
	}
	setLanguageMap(map) {
		for (var i in map) {
			map[map[i]] = i;
		}
		this.languageMap = map;
	}
	setLanguageData(languageName, data) {
		this.languageData[languageName] = data;

	}
}
let i18n = I18n.getInstance();

i18n.setLanguageMap(language_zh);

api('/Language/getLang', {
	Language: 'zh-CN'
}).then((res) => {
	if (res.code === 1 && res.data) {
		//  console.log(JSON.stringify(res.data))
		window.localStorage.setItem('language_zh', JSON.stringify(res.data));
		i18n.setLanguageMap(res.data);
		i18n.languageData['zh-CN'] = res.data;
		if (i18n.languageName === 'zh-CN') {
			i18n.language = i18n.languageData['zh-CN'];
		}
	}
});

api('/Language/getLang', {
	Language: 'en'
}).then((res) => {
	if (res.code === 1 && res.data) {
		//  console.log(JSON.stringify(res.data))
		window.localStorage.setItem('language_en', JSON.stringify(res.data));
		i18n.languageData['en'] = res.data;
		if (i18n.languageName === 'en') {
			i18n.language = i18n.languageData['en'];
		}
	}
});

export {
	i18n
}
